package fr.bda.cloud.tray.storage;

import javax.swing.JOptionPane;

import fr.bda.cloud.storage.LocalStorageUnitConfiguration;
import fr.bda.cloud.storage.StorageUnitConfiguration;
import fr.bda.cloud.tray.CloudTray;
import fr.bda.cloud.tray.CloudTrayDialog;
import fr.bda.cloud.tray.CloudTrayDialogController;
import fr.bda.cloud.tray.CloudTrayDialogDataValidator;

public class NewStorageUnitDialogValidator extends CloudTrayDialogDataValidator {

	public NewStorageUnitDialogValidator(CloudTray cloudTray) {
		super(cloudTray);
	}

	@Override
	public <C extends CloudTrayDialogController> boolean validate(CloudTrayDialog<C> dialog) {

		if (NewStorageUnitDialog.class.isInstance(dialog)) {

			NewStorageUnitDialog newStorageUnitDialog = (NewStorageUnitDialog) dialog;
			StorageUnitConfiguration storageUnitConfiguration = ((NewStorageUnitDialogController)newStorageUnitDialog.getController()).getStorageUnitConfiguration();

			// Validate already exist
			if (cloudTray.getData().getStorageUnitConfigurations().contains(storageUnitConfiguration)) {
				JOptionPane.showMessageDialog(dialog, "Storage unit [" + storageUnitConfiguration.getStorageUnitType().name() + "] already exist");
				return false;
			}

			// Validate StorageUnit configuration
			switch (storageUnitConfiguration.getStorageUnitType()) {
			case LOCAL:
				return validateLocalStorageUnit(dialog, storageUnitConfiguration);

			default:
				return true;
			}
		}

		return true;
	}

	private <C extends CloudTrayDialogController> boolean validateLocalStorageUnit(CloudTrayDialog<C> dialog, StorageUnitConfiguration storageUnitConfiguration) {

		if (LocalStorageUnitConfiguration.class.isInstance(storageUnitConfiguration)) {

			LocalStorageUnitConfiguration localStorageUnitConfiguration = (LocalStorageUnitConfiguration) storageUnitConfiguration;

			if (localStorageUnitConfiguration.getLocalFolder() == null) {
				JOptionPane.showMessageDialog(dialog, "Storage unit [" + storageUnitConfiguration.getStorageUnitType().name() + "] need a valid directory path");
				return false;
			} else if (!localStorageUnitConfiguration.getLocalFolder().exists()) {
				JOptionPane.showMessageDialog(dialog, "Storage unit [" + storageUnitConfiguration.getStorageUnitType().name() + "] need a valid directory path");
				return false;
			}

		}

		return true;
	}

}
